// pages/category/index.js
import {request} from '../../request/index.js';
import regeneratorRuntime from '../../lib/runtime/runtime.js';
import {getStorageCates,setStorageCates} from "../../utils/storage.js"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    leftMenuList: [],
    rightGoodsList: [],
    currentIndex: 0,
    scrollTop: 0
  },
  // 接口的返回值
  Cates: [],
  onLoad (){
    // 1.先获取缓存中的数据
    const readCates = getStorageCates();
    if(!readCates){

  // 2.没数据，重新请求
      this.getCategoryList();
    }else{
        // 有缓存，判断有没有过期
        if(Date.now()-readCates.time>1000*100){
         
          // 过期了
          this.getCategoryList();
        }else{
   
          const catesData=readCates.data;
          // 给全局变量赋值
          this.Cates = catesData;
          const leftMenuList = this.Cates.map((v) =>({cat_id:v.cat_id,cat_name:v.cat_name}));
          const rightGoodsList = this.Cates[0].children;
          this.setData({
            leftMenuList,
            rightGoodsList
          })
        }
    }
  },
  // 获取总数据
 async getCategoryList (){
    const result = await request({url:"/categories"});
              // 数据回来赋值给全局变量
      this.Cates=result;
      // 把数据存到本地
      setStorageCates({time:Date.now(),data:this.Cates});
        const leftMenuList = this.Cates.map((v) =>({cat_id:v.cat_id,cat_name:v.cat_name}));
        const rightGoodsList = this.Cates[0].children;
        this.setData({
          leftMenuList,
          rightGoodsList
        });
  },
  // 左侧菜单修改
     handleChangeMenu(e){
    // console.log(e)
    let {index} = e.currentTarget.dataset;
    const rightGoodsList = this.Cates[index].children;
    this.setData({
      currentIndex:index,
      rightGoodsList,
      scrollTop: 0
    });
  }
})